from datetime import datetime

from django.http import HttpResponse
from django.shortcuts import render
# 使用django封装好的connection对象，会自动读取settings.py中数据库的配置信息
from django.db import connection
from .models import Book
from django.db import models
from django.utils import timezone
# Create your views here.


##
def index(request):
    # 获取游标对象
    cursor = connection.cursor()
    # 拿到游标对象后执行sql语句
    cursor.execute("select * from book")
    # 获取所有的数据
    rows = cursor.fetchall()
    # 遍历查询到的数据
    for row in rows:
        print(row)
    return HttpResponse("查找成功! ")

## CRUD_add
def add(request):
    try:
        book = Book(name="雨季不再来", author="三毛",price=58.88)
        print(f"================{Book._meta.get_field('pub_time')}=====================")
        book.save()  # 尝试保存
        return HttpResponse("插入成功！")
    except Exception as e:
        return HttpResponse(f"发生错误：{e}")

## 查找数据
def query_books(request):
    ## 在 Django 中数据的查找 都是通过 模型下的 objects 对象来实现的
    #books = Book.objects.all
    #books2 = Book.objects.filter(name='西游记')
    #for  book  in books2:
    #    print(book.id,book.name,book.author,book.pub_time,book.price)
    ##

    try:
        books = Book.objects.get(name="西游记111")
        print(books.name)
    except Exception as e:
        return HttpResponse("图书不存在")
    return HttpResponse("数据查找成功！")

## 倒序排序
def orderview(request):
    books = Book.objects.order_by("-pub_time")
    for book in books:
        print(book.name)
    return HttpResponse("排序成功")

## update
def updateview(request):
    ## 获取数据
    book = Book.objects.first()
    book.name="Django入门到精通"
    book.pub_time = datetime.now()
    book.save()
    return HttpResponse("数据更新成功")

## delete
def deleteview(request):
    try:
        book = Book.objects.get(name="三国演义")
    except Exception as e:
        return HttpResponse("图书不存在")
    book.delete()
    return HttpResponse("图书删除成功")
